package com.smf.lsc.authorization.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.smf.lsc.authorization.security.handler.LoginFailureHandler;
import com.smf.lsc.authorization.security.handler.LoginInSuccessHandler;
import com.smf.lsc.authorization.security.service.MyUsernamePasswordAuthenticationFilter;

/**
 * 资源配置 Created on 2021/11/19.
 *
 * @author ln
 * @since 1.0
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

	@Value("${lsc.security.oauth2.permis-urls:''}")
	private String permisUrls;

	@Value("${lsc.security.oauth2.login-url:/login}")
	private String loginUrl;

	/**
	 * 自定义登录成功处理器
	 */
	@Autowired
	private LoginInSuccessHandler loginInSuccessHandler;

	/**
	 * 自定义登录失败处理器
	 */
	@Autowired
	private LoginFailureHandler loginFailureHandler;

	@Override
	public void configure(HttpSecurity http) throws Exception {

		String[] permisUrl = permisUrls.split(",");

		http.formLogin().successHandler(loginInSuccessHandler)// 登录成功处理器
				.and().authorizeRequests().antMatchers(permisUrl).permitAll().anyRequest().authenticated().and().csrf()
				.disable();
		http.addFilterBefore(myAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
	}

	@Autowired
	public AuthenticationManager authenticationManager;

	@Bean
	MyUsernamePasswordAuthenticationFilter myAuthenticationFilter() throws Exception {
		MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter(loginUrl);
		filter.setFilterProcessesUrl(loginUrl);
		filter.setAuthenticationManager(authenticationManager);
		filter.setAuthenticationSuccessHandler(loginInSuccessHandler);
		filter.setAuthenticationFailureHandler(loginFailureHandler);
		return filter;
	}

}
